<template>
  <div>
    <div class="search-wrap account-search">
      <div class="common-search ym-box">
        <el-form :model="queryForm" inline @submit.prevent>
          <el-form-item class="w-auto">
            <el-select v-model="queryType" placeholder="请选择" style="width: 120px">
              <el-option
                v-for="item in queryTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label class="w-auto">
            <search-input
              v-model="queryForm.name"
              :placeholder="inputPlaceholder"
              @search="search"
            />
            <!-- <el-input v-model="queryForm.query" :placeholder="inputPlaceholder" @keyup.enter="search">
            <template #append>
              <el-button style="vertical-align: middle;" @click="search">
                <el-icon>
                  <Search />
                </el-icon>
              </el-button>
            </template>
            </el-input>-->
          </el-form-item>
        </el-form>
        <refresh-btn @refresh="search" />
      </div>

      <el-button v-if="dep?.did" type="primary" class="btn-add" size="small" @click="create"
        >新用户</el-button
      >
    </div>

    <div class="table-wrap ym-box">
      <!-- :style="{ height: `calc(100vh - 70px - 10px -  40px - 74px - 20px - 48px) ` }"
      height="calc(100vh - 70px - 10px -  40px - 74px - 20px - 48px)"-->
      <ym-table
        v-loading="state.tableLoading"
        :data="state.tableData"
        :column-data="userColumnData"
        :style="{ height: `${tableHeight}px` }"
        :height="tableHeight"
      >
        <template #info="{ row }">
          <table-account-info :info="row" />
        </template>
        <template #groups="{ row }">
          <div class="group-list">
            <div v-for="(group, index) in row.groups" :key="index" class="group-item">
              <div>{{ group.name }}</div>
            </div>
          </div>
        </template>
        <template #loginDetail="{ row }">
          <div>计数：{{ row.loginNo }}</div>
          <div>最后登录：{{ row.loginTime }}</div>
        </template>
        <template #status="{ row }">
          <span class="status-wrap" :style="{ color: BASE_STATUS[row.status]?.color }">{{
            computedStatus(row.status)
          }}</span>
        </template>
        <template #operator="{ row }">
          <div>
            <el-button type="text" class="btn-edit" @click="editInit(row)">修改</el-button>
          </div>
          <div>
            <el-button type="text" class="btn-del" @click="del(row)">删除</el-button>
          </div>
        </template>
      </ym-table>

      <pagination
        v-model:currentPage="state.pageObj.pageNum"
        v-model:pageSize="state.pageObj.pageSize"
        class="account-page"
        :total="state.pageObj.total"
        @pagination="search"
      />
    </div>

    <drawer
      v-model:visible="state.dialogVisible"
      :size="640"
      :title="state.dialogTitle"
      @close="closeDrawer"
    >
      <add-or-edit-form
        ref="formWrapper"
        :form="_state.userForm"
        :is-add="state.isAdd"
        :role-data="roleData"
        @cancel="handleClose"
        @confirm="confirm"
      />
    </drawer>
  </div>
</template>

<script lang="ts" setup>
import { computed, defineExpose, defineProps, nextTick, reactive, ref, toRefs } from 'vue'

import RefreshBtn from '@/components/CommonSearch/RefreshBtn/index.vue'
import SearchInput from '@/components/CommonSearch/SearchInput/index.vue'
import TableAccountInfo from '@/components/UserInfo/TableAccountInfo.vue'
import AddOrEditForm from './AddOrEditForm.vue'

import { codeMaps, getByDictCodeList } from '@/api/backend/dict'
import RoleApi from '@/api/backend/role'
import UserApi from '@/api/backend/user'

import { getStyle } from '@/utils/dom'
import { userColumnData } from '&/utils/columnData'

import { BASE_STATUS } from '@/configs/codeMaps'
import { commonHandle } from '@/views/mixins/common'
import { Drawer, Pagination, YmTable } from '&/mixins/useComponent'
import IBaseObj from '#/index'

const tableHeight = ref(130)
const setTableHeight = () => {
  nextTick(() => {
    const options = {
      root: '#level-content',
      elements: [
        '#level-content .el-tabs__header',
        '#level-content .account-search',
        '#level-content .account-page',
      ],
      otherFunc: () => {
        const tablewrapPaddingTop = parseFloat(
          getStyle('#level-content .table-wrap')?.paddingTop || 0
        )
        const tablewrapPaddingtBottom = parseFloat(
          getStyle('#level-content .table-wrap')?.paddingBottom || 0
        )

        return tablewrapPaddingTop + tablewrapPaddingtBottom
      },
    }
    const { root, elements, otherFunc } = options
    const rootH = (document.querySelector(root) as HTMLElement)?.offsetHeight || 0
    let elementH = 0
    elements.forEach((ele) => {
      elementH += (document.querySelector(ele) as HTMLElement)?.offsetHeight || 0
    })
    const otherH = otherFunc()
    tableHeight.value = rootH - elementH - otherH
  })
}

const { state, handleAdd, handleEdit, handleClose, handleSearch, handleDelete } = commonHandle()

const queryTypeOptions = [
  {
    label: '姓名',
    value: 'name',
    placeholder: '输入姓名进行查询',
  },
  {
    label: '登录账号',
    value: 'loginCode',
    placeholder: '输入登录账号进行查询',
  },
  {
    label: '手机号',
    value: 'phone',
    placeholder: '输入手机号进行查询',
  },
  {
    label: '邮箱',
    value: 'email',
    placeholder: '请输入邮箱进行查询',
  },
]

const props = defineProps({
  dep: {
    type: Object,
    default: () => {},
  },
  oid: {
    type: [String, Number],
    default: '',
  },
  tableHeight: {
    type: Number,
    default: 0,
  },
})

const _state: IBaseObj = reactive({
  queryForm: {
    query: '',
  },
  queryType: 'name',
  userForm: {
    headPhoto: '',
    name: '',
    loginCode: '',
    phone: '',
    email: '',
    groups: [],
    gender: '',
    birthday: '',
    jobPost: '',
    // sysRole: 1202,
    role: [],
    did: '',
    oid: '',
  },
  statusOptions: [],
  roleData: {},
})

const { queryForm, queryType, roleData } = toRefs(_state)

const inputPlaceholder = computed(() => {
  return queryTypeOptions.filter((val) => val.value === _state.queryType)[0].placeholder
})

const computedStatus = (status: number) => {
  return _state.statusOptions.find((v: IBaseObj) => v.code === status)?.value
}

const getDictData = async () => {
  const ret = await getByDictCodeList([codeMaps.status])
  _state.statusOptions = ret && ret[codeMaps.status]
}
getDictData()

const getRoleData = async () => {
  const ret = await RoleApi.getDefaultRolesList()
  _state.roleData = ret || {}
}
getRoleData()

const search = () => {
  handleSearch(UserApi.getUserByPage, {
    [_state.queryType]: _state.queryForm.query,
    did: props.dep.did,
    oid: props.oid,
  })
}

const create = () => {
  console.log('p', props.dep)
  _state.userForm.did = props.dep.did
  _state.userForm.oid = props.oid
  handleAdd('创建用户')
}

const editInit = async (row: IBaseObj) => {
  const ret = await UserApi.getUserById(row.uid)
  if (ret.data) {
    handleEdit('修改用户')
    _state.userForm = ret.data
  }
}

const del = (row: IBaseObj) => {
  handleDelete({
    url: UserApi.delUrl,
    id: row.uid,
    message: '此操作将永久删除该用户，是否继续?',
    success: search,
  })
}

const formWrapper = ref()
const addOrEditReset = () => {
  formWrapper.value.clear()
  _state.userForm = {
    headPhoto: '',
    name: '',
    loginCode: '',
    phone: '',
    email: '',
    groups: [],
    gender: '',
    birthday: '',
    jobPost: '',
    // sysRole: 1202,
    role: [],
  }
}

const closeDrawer = () => {
  state.isAdd = true
  addOrEditReset()
}

const confirm = () => {
  handleClose()
  search()
}

defineExpose({
  search,
  setTableHeight,
})
</script>

<style lang="scss" scoped>
.search-wrap {
  justify-content: space-between !important;
}
</style>
